package com.zhj.rpc.netty;

import com.zhj.rpc.pojo.URL;
import com.zhj.rpc.register.NativeRegistry;
import com.zhj.rpc.service.HelloService;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.lang.reflect.Method;

/**
 * @author zhj
 */
public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 获取客户端发送的消息, 并调用服务
        System.out.println("log.info:msg= " + msg);
        // 客户端在调用服务器的api时，我们需要定义一个协议
        // 每次发消息时必须以某个字符串开头
        if (msg.toString().startsWith("RPC-Dubbo-Hello#zhj#")) {
            Class implClass = NativeRegistry.get(HelloService.class.getName(), new URL("127.0.0.1", 8080));
            Method sayHello = implClass.getMethod("sayHello", String.class);
            String result = (String) sayHello.invoke(implClass.newInstance(),  msg.toString().substring(msg.toString().lastIndexOf("#") + 1));
            System.out.println("向客户端返回结果为：" + result);
            ctx.writeAndFlush(result);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
